﻿using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System.Text;

namespace Future.Common.Utils
{
    /// <summary>
    /// 描述：缓存扩展方法
    /// 创建人： yangkai
    /// 创建时间：2022/12/18 16:05:40
    /// </summary>
    public static class IDistributedCacheExtension
    {
        /// <summary>
        /// 缓存对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        public static void SetObject<T>(this IDistributedCache cache, string key, T obj) where T : class
        {
            cache.SetString(key, obj.ToJson(true));
        }

        /// <summary>
        /// 缓存对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="ExpirationTime">缓存过期时间单位分钟</param>
        public static void SetObject<T>(this IDistributedCache cache, string key, T obj, int ExpirationTime) where T : class
        {
            DistributedCacheEntryOptions distributedCacheEntryOptions = new();
            distributedCacheEntryOptions.SetAbsoluteExpiration(TimeSpan.FromMinutes(ExpirationTime));

            cache.SetString(key, obj.ToJson(true), distributedCacheEntryOptions);
        }

        /// <summary>
        /// 从缓存读取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T? GetObject<T>(this IDistributedCache cache, string key) where T : class
        {
            string? value = cache.GetString(key);
            if (value == null)
            {
                return null;
            }

            return JsonConvert.DeserializeObject<T>(value);
        }
    }
}
